// websocket 连接+消息发送
package controllers

import (
	"gohub/pkg/websocket"
	"net/http"

	"github.com/gin-gonic/gin"
)

type WebSocketController struct {
	manager *websocket.WebSocketManager
}

func NewWebSocketController(manager *websocket.WebSocketManager) *WebSocketController {
	return &WebSocketController{
		manager: manager,
	}
}

// Connect 处理WebSocket连接
func (wc *WebSocketController) Connect(c *gin.Context) {
	wc.manager.HandleConnection(c)
}

// Broadcast 广播消息
func (wc *WebSocketController) Broadcast(c *gin.Context) {
	var req struct {
		Message string `json:"message" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	//wc.manager.Broadcast <- []byte(req.Message)
	wc.manager.SendBroadcast([]byte(req.Message))
	c.JSON(http.StatusOK, gin.H{"status": "broadcast sent"})
}

// SendToClient 发送消息到指定客户端
func (wc *WebSocketController) SendToClient(c *gin.Context) {
	clientID := c.Param("client_id")

	var req struct {
		Message string `json:"message" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if ok := wc.manager.SendToClient(clientID, []byte(req.Message)); !ok {
		c.JSON(http.StatusNotFound, gin.H{"error": "client not found"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": "message sent"})
}

// SendToUser 发送消息到指定用户
func (wc *WebSocketController) SendToUser(c *gin.Context) {
	userID := c.Param("user_id")

	var req struct {
		Message string `json:"message" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	count := wc.manager.SendToUser(userID, []byte(req.Message))
	c.JSON(http.StatusOK, gin.H{"status": "messages sent", "count": count})
}

// GetClients 获取所有客户端状态
func (wc *WebSocketController) GetClients(c *gin.Context) {
	clients := wc.manager.GetAllClients()
	c.JSON(http.StatusOK, gin.H{"clients": clients})
}
